package com.znsd.zl.app.user.utils;

import com.alibaba.fastjson.JSONObject;
import com.znsd.zl.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * <p>
 *     获取微信用户凭证工具类
 * </p>
 *
 * @ClassName LoginCredentialsUtils
 * @Description 通过code获取微信用户登录凭证
 * @Author jaypdd
 * @Date 2020/8/25 11:50
 * @Version v1.0
 */
@Slf4j
@Component
public class LoginCredentialsUtils {

	private static final String WE_CHAT_REQUEST_ERROR = "errcode";

	/**
	 * 小程序 appId
	 */
	@Value("${wechat.appid}")
	private String appId;

	/**
	 * 小程序 appSecret
	 */
	@Value("${wechat.secret}")
	private String secret;

	/**
	 * code换取授权Token请求地址
	 */
	@Value("${wechat.token-url}")
	private String url;

	/**
	 * 通过code换取凭证
	 * @param code  登录时获取的 code
	 * @return  返回凭证信息
	 */
	public JSONObject getCredentials(String code) {
		// 封装http请求通过code换取凭证信息
		String httpUrl = url + "?appid=" + appId + "&secret=" + secret
				+ "&js_code=" + code + "&grant_type=authorization_code";
		OkHttpClient client = new OkHttpClient();
		Request request = new Request.Builder().url(httpUrl).build();

		// 获取凭证信息
		JSONObject jsonObject = null;
		try {
			Response response = client.newCall(request).execute();
			if ( response.isSuccessful() ) {
				String str = response.body().string();
				jsonObject = JSONObject.parseObject(str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 凭证信息获取失败
		if ( jsonObject.containsKey(WE_CHAT_REQUEST_ERROR) ) {
			log.error("【小程序授权】code换取openId失败，请求参数：{}，失败原因：{}", request, jsonObject.toJSONString());
			throw new RRException("认证失败，请稍后重试");
		}

		return jsonObject;
	}

}
